<?php

namespace App\Api\Controllers;

use App\Models\Demand;
use App\Models\User;
use App\Models\Depot;
use App\Models\Goods;
use Dingo\Api\Http\Request;
use Dingo\Api\Routing\Helpers;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\WeChat\WxTrait;


class DepotController extends Controller
{
    use Helpers;
    use WxTrait;

    //书架首页列表
    public function index()
    {
        $user = $this->auth->user();
        return $this->response->array([
            'status_code' => 200,
            'message' => '获取数据成功',
            'result' => $this->getDepotByUserId($user->id)
        ]);
    }

    /**
     * 名称：书架列表
     * 必要条件：userId
     * 任务：返回书架列表，标题，和当前用户是否为本人
     */
    public function getDepotList($shareCode)
    {
        $user = $this->auth->user();
        if($user->share_code==$shareCode){
            $data['self']=true;
        }else{
            $data['self']=false;
            $user=User::where('share_code',$shareCode)->first();
        }
        if(!$user){
            return $this->response->array([
                'status_code' => 201,
                'message' => '不存在的用户',
            ]);
        }
        $data['title']='我的小书店';
        $data['list']=$this->getDepotByUserId($user->id);
        $data['userInfo']=$user;
        return $this->response->array([
            'status_code' => 200,
            'message' => '获取数据成功',
            'result' =>$data
        ]);
    }

    private function getDepotByUserId($userId){
        $data = DB::table('depot as d')
            ->leftJoin('goods as g', 'd.goods_id', '=', 'g.id')
            ->where('d.user_id', $userId)
            ->select('d.id', 'd.total','d.can_sale_num', 'g.img', 'g.title', 'g.author', 'g.publisher', 'g.price', 'g.discount','g.id as goods_id',
                DB::raw('if(can_sale_num>0,goods_status,0) as goods_status')
            )
            ->get();
        foreach ($data as $v) {
            $v->price = sprintf('%.2f', $v->price * $v->discount / 100);
        }
        return $data;
    }
    /**
     * @param $id
     * @return mixed
     * 展示书架中商品详情
     */
    public function depotDetail($id)
    {
        $data = DB::table('depot as d')
            ->leftJoin('goods as g', 'd.goods_id', '=', 'g.id')
            ->where([['d.id', $id], ['user_id', $this->user->id]])
            ->select('d.id', 'd.total', 'd.lock_num', 'd.goods_status', 'g.img_large as img', 'g.title', 'g.author', 'g.publisher', 'g.price', 'g.discount')
            ->first();
        return $this->response->array([
            'message' => '获取书籍成功',
            'status_code' => 200,
            'result' => $data
        ]);
    }

    /**
     * @param $isbn
     * @return array
     * 扫码信息预览。
     * 若未找到书籍则需要记录isbn ，发送模板消息给管理员。通知其增加书籍
     */
    public function depotShow($isbn)
    {
        $user=$this->auth->user();
        $goods = $this->getGoodsInfo($isbn);
        if ($goods) {
            return $this->response->array(['status_code' => 200, 'message' => '获取书籍信息成功','result'=>$goods]);
        }else{
            $demand=Demand::where('isbn',$isbn)->first();
            if($demand){
                $openids=explode(',',$demand->openid);
                if(!in_array($user->openid,$openids)){
                    $openids[]=$user->openid;
                    $demand->openid=implode(',',$openids);
                    $demand->save();
                }
            }else{
                $data=[
                    'openid'=>$user->openid,
                    'isbn'=>$isbn,
                    'is_dealed'=>0,
                    'send_user'=>0,
                    'send_manager'=>0,
                    'fail_id'=>''
                ];
                $demand=Demand::create($data);
            }

            if($demand && $demand->send_manager==0){
                //创建成功，则向管理员发送模板消息
                $needDealNum=Demand::where('is_dealed',0)->count();
                $content=[
                    'first'=>'扫码失败的书籍处理',
                    'keyword1'=>'需要处理',
                    'keyword2'=>'未增加',
                    'keyword3'=>'请您尽快登录管理平台，处理用户扫码失败后的isbn',
                    'remark'=>'待处理数量:'.$needDealNum.'条'
                ];
                $managerOpenids=DB::table('users')->where('manager',1)->pluck('openid');

                if(count($managerOpenids)!=0){
                    //存在管理元，则发送模板消息通知管理员
                    if(count($managerOpenids)!=0){
                        foreach($managerOpenids as $v){
                            $res=$this->prepareMessage($v,2,$content);
                            if(!$res['result']){
                                if($res['fail_id']){
                                    $demand->fail_id.= $res['fail_id'].',';
                                }
                            }
                        }
                        if(!$demand->fail_id){
                            $demand->send_manager=1;
                        }
                        $demand->save();
                    }
                }

            }
            return $this->response->array(['status_code' => 201, 'message' => '抱歉，书籍信息没有找到，我们将会尽快收录此书籍，']);
        }
    }

    //为书架添加新的书籍
    public function store($isbn)
    {
        $user = $this->auth->user();
        $goods = $this->getGoodsInfo($isbn);
        if($goods){
            if(Depot::where([['user_id', $user->id], ['goods_id', $goods->id]])->first()){
                return $this->response->array([
                    'status_code' => 201,
                    'message' => '您书架中已存在该书籍'
                ]);
            }else{
                $depotData = [
                    'user_id' => $user->id,
                    'goods_id' => $goods->id,
                    'campus_id' => $user->campus_id,
                    'goods_status' => 1,//在销售
                    'university_id' => $user->university_id,
                    'total' => 1,
                    'can_sale_num' => 1,
                    'lock_num' => 0,
                ];
                if (Depot::create($depotData)) {
                    return $this->response->array(['status_code' => 200, 'message' => '上架成功']);
                } else {
                    return $this->response->array(['status_code' => 201, 'message' => '上架失败']);
                }
            }
        }else{
            return $this->response->array([
                'status_code' => 201,
                'message' => '上架失败，未找到相关书籍'
            ]);
        }


    }

    /**
     * @param $isbn
     * @return $this|array|\Illuminate\Database\Eloquent\Model|null|static
     * 这个函数有三个地方在调用
     * 功能：通过isbn ，查询书籍信息，若平台中没有则请求豆瓣api,然后将书籍信息拉取到数据库中
     */
    public function getGoodsInfo($isbn)
    {
        $isbn=trim($isbn,' ');
        $isbnLen = strlen($isbn);
        if ($isbnLen != 10 && $isbnLen != 13) {
            return ['result' => 0, 'message' => '数据不合法'];
        }
        //先查询自身数据库中是否存在该书籍
        $goods = Goods::where('isbn13', $isbn)->orWhere('isbn10', $isbn)->first();
        if (!$goods) {
            $url = 'https://api.douban.com/v2/book/isbn/' . $isbn;
            $data = json_decode(get_data($url));
            if (isset($data->code) && $data->code == 6000) {
                return null;
            }
            $dataIn = [
                'author' => implode(',', $data->author),
                'author_intro' => $data->author_intro,
                'img_small' => $data->images->small,
                'img_medium' => $data->images->medium,
                'img_large' => $data->images->large,
                'img' => $data->image,
                'isbn10' => $data->isbn10,
                'isbn13' => $data->isbn13,
                'pages' => $data->pages,
                'price' => str_replace(['CNY', '元'], '', $data->price) ?: 43,//没有价格的书籍就定为43块吧
                'pubdate' => $data->pubdate,
                'publisher' => $data->publisher,
                'summary' => $data->summary,
                'title' => $data->title,
            ];
            //获取加入书籍时的后台配置的折扣
            $dataIn['discount'] = web_config('value') ?: 20;
            $goods = Goods::create($dataIn);
        }
        return $goods;

    }

    //更新书架书籍数量，可销售状态
    public function update(Request $request, $id)
    {
        $total = $request->input('total', 1);
        $goods_status = $request->input('goods_status', 0);
        $depot = Depot::find($id);
        //书籍数量不能小于0
        if ($total < 0) {
            return $this->response->array([
                'status_code' => 201,
                'message' => '书籍总量不能小于0'
            ]);
        }
        //书籍总量不能小于锁定数量
        if ($total < $depot->lock_num) {
            return $this->response->array([
                'status_code' => 201,
                'message' => '书籍总量不能小于锁定数量'
            ]);
        }
        //当书籍总量为0时，书籍状态不能更改为销售中
        if ($total == 0 && $goods_status > 0) {
            return $this->response->array([
                'status_code' => 201,
                'message' => '非法修改'
            ]);
        }
        $depot->total = $total;
        $depot->can_sale_num = $depot->total - $depot->lock_num;
        $depot->goods_status = $goods_status;
        if ($depot->save()) {
            return $this->response->array([
                'status_code' => 200,
                'message' => '操作成功'
            ]);
        } else {
            return $this->response->array([
                'status_code' => 201,
                'message' => '操作失败'
            ]);
        }

    }


}